package com.ts.api.module.product.service.impl;

import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.ts.api.module.channel.entity.po.ChannelUserProductMatchPO;
import com.ts.api.module.product.dao.ProductPlanDao;
import com.ts.api.module.product.dao.ProductUserMatchDao;
import com.ts.api.module.product.entity.po.ProductPlanPO;
import com.ts.api.module.product.entity.qo.ProductPlanQO;
import com.ts.api.module.product.service.ProductPlanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ProductPlanServiceImpl implements ProductPlanService {

    @Autowired
    private ProductPlanDao productPlanDao;
    @Autowired
    private ProductUserMatchDao productUserMatchDao;

    @Override
    @Transactional(readOnly = true)
    public ProductPlanPO get(Long id) {
        return productPlanDao.get(id);
    }

    @Override
    @Transactional(readOnly = true)
    public List<ProductPlanPO> list(ProductPlanQO productPlanQO) {
        return productPlanDao.list(productPlanQO);
    }

    @Override
    @Transactional(readOnly = true)
    public List<ProductPlanPO> listByProductId(Long productId) {
        return productPlanDao.listByProductId(productId);
    }

    @Override
    public List<ProductPlanPO> filterDistributeByUser(List<ProductPlanPO> listMatchPlan, Long userId) {
        List<ProductPlanPO> listMatchPlanCopy = CollUtils.copy(listMatchPlan);
        //  获取该用户所有已经匹配的计划
        List<ChannelUserProductMatchPO> listUserProductMatch = productUserMatchDao.listProductMatchByUserId(userId);
        //  排重匹配计划id
        List<Long> listExcludeProductId = CollUtils.distinct(listUserProductMatch, ChannelUserProductMatchPO::getLoanProductId);
        //  排重匹配计划中存在此用户
        CollUtils.filter(listMatchPlanCopy, t -> listExcludeProductId.contains(t.getLoanProductId()));
        return listMatchPlanCopy;
    }

    @Override
    public List<ProductPlanPO> filterDistributeLocalCrmByUser(List<ProductPlanPO> listMatchPlan, Long userId) {
        //  获取该用户所有已经匹配的本地计划
        List<ChannelUserProductMatchPO> listUserProductMatch = productUserMatchDao.listProductMatchLocalCrmByUserId(userId);
        if (ValidParam.isEmpty(listUserProductMatch)) {
            return listMatchPlan;
        }

        //  拷贝源数据
        List<ProductPlanPO> listMatchPlanCopy = CollUtils.copy(listMatchPlan);
        //  排重匹配计划id
        List<Long> listExcludeProductId = CollUtils.distinct(listUserProductMatch, ChannelUserProductMatchPO::getLoanProductId);
        //  排重匹配计划中存在此用户
        CollUtils.filter(listMatchPlanCopy, t -> listExcludeProductId.contains(t.getLoanProductId()));
        return listMatchPlanCopy;
    }
}
